import { Image, Text, View, ScrollView } from '@tarojs/components';
import Taro from '@tarojs/taro';
import { toJS } from 'mobx';
import { observer } from "mobx-react-lite";
import { useEffect, useRef } from 'react';
import utils from 'src/utils/utils';
import styles from './goodsTemlate.module.less';
import goodsTemlateStore from './goodsTemlateStore';
import { DesignData, GoodsData } from 'types/type';

// 商品模板页 - Tab切换版本
const GoodsTemlate = observer(() => {
    // 在 H5 环境中更可靠的获取路由参数的方式
    const getQueryParams = () => {
        if (process.env.TARO_ENV === 'h5') {
            // H5 环境下直接从 URL 获取参数
            const queryString = window.location.search;
            const urlParams = new URLSearchParams(queryString);
            return Object.fromEntries(urlParams.entries());
        } else {
            // 非 H5 环境使用 Taro 的方式
            return Taro.getCurrentInstance().router?.params || {};
        }
    };

    const { productNegativeId } = getQueryParams();
    const scrollViewRef = useRef<typeof ScrollView>(null);

    // 从store中获取状态和方法
    // 基本类型状态值使用解构方式获取
    const { activeTabIndex, loadMoreLoading, hasMore } = goodsTemlateStore;

    // 数组或对象类型状态值使用toJS方法获取
    const templateCategories = toJS(goodsTemlateStore.templateCategories);
    const visibleCategories = toJS(goodsTemlateStore.visibleCategories);
    const activeCategory = toJS(goodsTemlateStore.activeCategory);
    const displayedDesigns = toJS(goodsTemlateStore.displayedDesigns);

    useEffect(() => {
        goodsTemlateStore.getTemplatesByNegativeId(68);
        // goodsTemlateStore.getTemplatesByNegativeId(Number(productNegativeId));
    }, []);

    return (
        <View className={styles.tabContainer}>
            {/* Tab栏 */}
            <View className={styles.tabBar}>
                <View className={styles.tabScrollView}>
                    {visibleCategories.map((category, index) => (
                        <View
                            key={category.templateId || `tab-${index}`}
                            className={`${styles.tabItem} ${index === activeTabIndex ? styles.activeTab : ''}`}
                            onClick={() => goodsTemlateStore.handleTabChange(index)}
                        >
                            <Text className={`${styles.tabText} ${index === activeTabIndex ? styles.activeTabText : ''}`}>
                                {category.templateName || '未命名模板'}
                            </Text>
                        </View>
                    ))}
                </View>
            </View>

            {/* 内容区域 */}
            <View className={styles.tabContent}>
                {activeCategory && (
                    <ScrollView
                        key={activeCategory.templateId}
                        className={styles.templateList}
                        ref={scrollViewRef}
                        scrollY
                        onScroll={e => goodsTemlateStore.handleScroll(e)}
                        lowerThreshold={100}
                        // 滚动到底部时触发加载更多
                        onScrollToLower={() => goodsTemlateStore.loadMore()}
                    >
                        {displayedDesigns.length > 0 ? (
                            displayedDesigns.map((design, index) => (
                                <View
                                    key={design.id || design.designId || `design-${index}`}
                                    className={styles.templateItem}
                                    onClick={() => goodsTemlateStore.handleSelectTemplate(design.data || design)}
                                >
                                    <Image
                                        src={utils.ossSuffix(design.picUrl || design.picUrls || '', 240)}
                                        className={styles.templateImage}
                                        mode="aspectFit"
                                    />
                                </View>
                            ))
                        ) : (
                            <View className={styles.emptyContainer}>
                                <Text className={styles.emptyText}>暂无模板数据</Text>
                            </View>
                        )}

                        {/* 加载更多状态 */}
                        {loadMoreLoading &&
                            (
                                <View className={styles.loadingContainer}>
                                    <Text className={styles.loadingText}>加载中...</Text>
                                </View>
                            )
                        }

                        {/* 没有更多数据状态 */}
                        {!hasMore && displayedDesigns.length > 0 &&
                            (
                                <View className={styles.loadingContainer}>
                                    <Text className={styles.loadingText}>没有更多数据了</Text>
                                </View>
                            )
                        }
                    </ScrollView>
                )}
            </View>
        </View>
    );
});

export default GoodsTemlate;